package com.power.web.action.question;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.power.Constants;
import com.power.model.department.TiDepartment;
import com.power.model.group.TiGroup;
import com.power.model.hospital.TiHospital;
import com.power.model.member.TmMember;
import com.power.model.question.TiQuestion;
import com.power.model.tiCase.TICase;
import com.power.model.user.TsSysuser;
import com.power.services.department.DepartmentService;
import com.power.services.district.TsDistrictService;
import com.power.services.group.TiGroupService;
import com.power.services.hospital.HospitalService;
import com.power.services.question.TiQuestionService;
import com.power.util.BASE64Util;
import com.power.util.CharacterUtil;
import com.power.util.DateJsonValueProcessor;
import com.power.util.RequestUtil;
import com.power.util.mail.MailInfo;
import com.power.util.mail.MailUtil;
import com.power.web.action.base.AbstractBaseAction;

public class TiQuestionAction extends AbstractBaseAction {
    
    private static final long serialVersionUID = 4628301066492657392L;
    
    private String jsonString;
    
    @Autowired
    private TiQuestionService service;
    
    @Autowired
    private HospitalService hosService;
    
    @Autowired
    private DepartmentService departService;
    
    @Autowired
    private TiGroupService groupService;
    
    private TiQuestion tiQuestion;
    
    private List<TiQuestion> tiQuestionList;
    
    private String flag;
    
    public String findInfoList() {
        try {
            TsSysuser userInfo = (TsSysuser)this.session.get(Constants.USERINFO_KEY);
            tiQuestionList = service.findListByMemberId(userInfo.getMemberid());
        }
        catch (Exception e) {
        }
        return "tiQuestionList";
    }
    
    public String editQuestion() {
        Integer id = RequestUtil.getParam(request, "id", 0);
        tiQuestion = service.read(id);
        if (tiQuestion == null) {
            tiQuestion = new TiQuestion();
            tiQuestion.setIsReply("2");
        }
        return "addNewQuestion";
    }
    
    public String updateQuestion() {
        try {
            TsSysuser userInfo = (TsSysuser)this.session.get(Constants.USERINFO_KEY);
            tiQuestion.setCreateAuthor(userInfo.getMemberid());
            tiQuestion.setCreateMan(userInfo.getRealName());
            tiQuestion.setCreateEmail(userInfo.getEmail());
            tiQuestion.setCreateTime(new Date());
            Integer groupId = (Integer)this.request.getSession().getAttribute("groupId");
            if (null != groupId && groupId > 0) {
                tiQuestion.setGroupId(groupId);
                TiGroup group = groupService.read(groupId);
                TiDepartment dep = departService.read(group.getDid());
                TiHospital hos = hosService.read(group.getHid());
                tiQuestion.setGroupName(hos.getName() + "-" + dep.getName() + "-" + group.getName());
                this.request.getSession().removeAttribute("groupId");
            }
            if (null != tiQuestion.getId())
                service.update(tiQuestion);
            else
                service.create(tiQuestion);
            tiQuestionList = service.findListByMemberId(userInfo.getMemberid());
        }
        catch (Exception e) {
        }
        return "saveSuccess";
    }
    
    public String deleteQuestion() {
        try {
            TsSysuser userInfo = (TsSysuser)this.session.get(Constants.USERINFO_KEY);
            Integer id = RequestUtil.getParam(request, "id", 0);
            tiQuestion = service.read(id);
            service.delete(tiQuestion);
            tiQuestionList = service.findListByMemberId(userInfo.getMemberid());
        }
        catch (Exception e) {
        }
        return "saveSuccess";
    }
    
    /**
     * 查询求诊信息
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public String searchQuestion() {
        try {
            int start = this.start;
            int limit = this.limit;
            if (limit == 0)
                limit = 20;
            Integer replyFlag = RequestUtil.getParam(request, "replyFlag", -1);
            String startDate = RequestUtil.getParam(this.request, "startTime", "-1");
            String endDate = RequestUtil.getParam(this.request, "endTime", "-1");
            String title = CharacterUtil.encode(RequestUtil.getParam(request, "title", ""));
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("start", start + "");
            paraMap.put("limit", limit + "");
            paraMap.put("replyFlag", replyFlag.toString());
            paraMap.put("startDate", startDate);
            paraMap.put("endDate", endDate);
            paraMap.put("title", title);
            Map<String, Object> dataMap = service.findTiQuestion(paraMap);
            StringBuffer jsonStr = new StringBuffer();
            String callback = this.callback;
            List<TiQuestion> data = (List<TiQuestion>)dataMap.get("data");
            int count = Integer.parseInt(dataMap.get("count").toString());
            jsonStr.append(callback).append("({\"total\":").append(count).append(",\"results\":");
            JsonConfig jsonconfig = new JsonConfig();
            jsonconfig.registerJsonValueProcessor("createTime", new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
            jsonconfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor(
                "yyyy-MM-dd HH:mm:ss"));
            JSONArray arry = JSONArray.fromObject(data, jsonconfig);
            jsonStr.append(arry.toString());
            jsonStr.append("})");
            this.jsonString = jsonStr.toString();
            
        }
        catch (Exception e) {
            log.error("病例查询失败！", e);
            this.jsonString = "[]";
        }
        this.response.setCharacterEncoding("UTF-8");
        try {
            this.response.getWriter().print(jsonString);
        }
        catch (IOException e) {
            log.error("病例查询io异常!", e);
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 
     * 删除求诊信息
     * 
     * @return
     */
    public String delTiQuestion() {
        try {
            String json = "{failure:true,msg:'求诊信息删除失败！'}";
            String deleteIds = request.getParameter("deleteID");
            service.delete(deleteIds);
            json = "{success:true, msg:'求诊信息删除成功！'}";
            this.response.setCharacterEncoding("UTF-8");
            this.response.getWriter().print(json);
        }
        catch (Exception e) {
            log.error("求诊信息删除失败！", e);
        }
        return null;
    }
    
    /**
     * 查看求诊信息
     * 
     * @return
     */
    public String showPage() {
        Integer id = RequestUtil.getParam(request, "id", 0);
        try {
            tiQuestion = service.read(id);
        }
        catch (Exception e) {
            log.error("获取数据错误");
            e.printStackTrace();
        }
        return "showPage";
    }
    
    /**
     * 回复
     * 
     * @return
     */
    public String replyQuestion() {
        Integer ifsendEmail = RequestUtil.getParam(request, "ifsendEmail", 1);
        try {
            if (null != tiQuestion.getId()) {
                TiQuestion question = service.read(tiQuestion.getId());
                TsSysuser userInfo = (TsSysuser)this.session.get(Constants.USERINFO_KEY);
                question.setReplyAuthor(userInfo.getId());
                question.setReplyMan(userInfo.getRealName());
                question.setReplyTime(new Date());
                question.setHasReply(tiQuestion.getHasReply());
                question.setIsReply(tiQuestion.getIsReply());
                if ("3".equals(tiQuestion.getIsReply())) {
                    service.saveOrUpdate(question);
                }
                else {
                    if (ifsendEmail == 1)// 1直接回复 2发邮件并回复
                        service.saveOrUpdate(question);
                    else {
                        boolean flag = registerSendMail(question, userInfo);
                        if (flag) {
                            service.saveOrUpdate(question);
                        }
                    }
                }
                request.setAttribute("ifsuccess", "保存成功!");
            }
        }
        catch (Exception e) {
            request.setAttribute("ifsuccess", "保存失败!");
            e.printStackTrace();
        }
        return "ifsuccess";
    }
    
    /**
     * 求诊信息 回复发送邮件
     * 
     * @return
     */
    public boolean registerSendMail(TiQuestion question, TsSysuser userInfo) {
        boolean flag = false;
        try {
            String email = question.getCreateEmail();
            MailInfo mailInfo = new MailInfo();
            mailInfo.setSmtpServer("smtp.126.com");
            // mailInfo.setMailFrom("the_doctor_online@126.com");
            mailInfo.setUserName("rosham");
            // mailInfo.setPassword("test123");
            mailInfo.setMailFrom("rosham@126.com");
            mailInfo.setMailTo(email);
            // mailInfo.setMailTo("zhh0908@126.com");
            // mailInfo.setUserName("医院在线系统");
            mailInfo.setPassword("zhenghao1011");
            mailInfo.setTitle("医生在线系统 – 求诊信息回复！");
            mailInfo.setText("亲爱的用户，您好！感谢您使用本系统。\r\n \r\n");
            mailInfo.setText(mailInfo.getText() + "                        我们已收到了您的求诊信息:" + question.getTitle()
                + "。现回复如下：" + "  \r\n \r\n");
            mailInfo.setText(mailInfo.getText() + "                        " + question.getHasReply() + "  \r\n \r\n");
            mailInfo.setText(mailInfo.getText() + "                                         感谢您使用医院在线系统\r\n");
            mailInfo.setText(mailInfo.getText()
                + "--------------------------------------------------------------------------------------------------\r\n\r\n");
            mailInfo.setText(mailInfo.getText() + "                        此信由系统发出，不接收回信，请勿直接回复。\r\n\r\n");
            mailInfo.setText(mailInfo.getText()
                + "                        如有任何疑问，请与客服人员联系或者访问http://www.9898sj.com/attendances与我们取得联系。\r\n\r\n\r\n");
            mailInfo.setText(mailInfo.getText()
                + "                                                                医生在线系统版权所有");
            if (MailUtil.sendMail(mailInfo)) {
                flag = true;
            }
        }
        catch (Exception e) {
            log.error("邮件发送失败！", e);
        }
        return flag;
    }
    
    public String getJsonString() {
        return jsonString;
    }
    
    public void setJsonString(String jsonString) {
        this.jsonString = jsonString;
    }
    
    public TiQuestion getTiQuestion() {
        return tiQuestion;
    }
    
    public void setTiQuestion(TiQuestion tiQuestion) {
        this.tiQuestion = tiQuestion;
    }
    
    public List<TiQuestion> getTiQuestionList() {
        return tiQuestionList;
    }
    
    public void setTiQuestionList(List<TiQuestion> tiQuestionList) {
        this.tiQuestionList = tiQuestionList;
    }
    
    public String getFlag() {
        return flag;
    }
    
    public void setFlag(String flag) {
        this.flag = flag;
    }
}
